import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'
import App from './app.vue'
import {
  resolve
} from 'dns';

Vue.use(VueRouter)
Vue.use(Vuex)

const Routers = [{
    path: '/index',
    meta: {
      title: '首页',
    },
    component: (resolve) => require(['./views/index.vue'], resolve)
  },
  {
    path: '/about',
    meta: {
      title: '关于',
    },
    component: (resolve) => require(['./views/about.vue'], resolve)
  },
  {
    path: '/user/:id',
    meta: {
      title: '个人主页',
    },
    component: (resolve) => require(['./views/user.vue'], resolve)
  },
  {
    path: '/message',
    meta: {
      title: '消息',
    },
    component: (resolve) => require(['./views/message.vue'], resolve)
  },
  {
    path: '/*',
    redirect: '/index'
  }
]

const RouterConfig = {
  mode: 'hash',
  routes: Routers,
  base: '/vuex/'
}

const router = new VueRouter(RouterConfig)

router.beforeEach((to, from, next) => {
  window.document.title = to.meta.title
  next()
})

console.log(router.currentRoute)

const store = new Vuex.Store({
  // Vuex配置
  // 只读访问： this.$store.state.count 
  state: {
    count: 0,
    list: [1, 5, 8, 10, 30, 50]
  },
  // 只读可变访问： this.$store.getters.filteredList
  getters: {
    filteredList: state => {
      return state.list.filter(item => item < 10)
    },
    listCount: (state, getters) => {
      return getters.filteredList.length
    }
  },
  // 直接更新必须通过 mutations
  // 用法： this.$store.commit('increment')
  // 用法： this.$store.commit('increment', 1)
  // 用法： this.$store.commit({type: 'increment', count: 10})
  mutations: {
    increment(state, n = 1) {
      state.count += n
    },
    incrementM(state, params) {
      state.count += params.count
    },
    decrease(state) {
      state.count--
    }
  },
  // 异步更新必须通过 actions
  // 用法： this.$store.dispatch('increment').then(() => {})
  actions: {
    increment(context) {
      context.commit('increment')
    },
    asyncIncrement(context) {
      return new Promise(resolve => {
        setTimeout(() => {
          context.commit('increment')
          resolve()
        }, 1000)
      })
    }
  }
})

new Vue({
  el: '#app',
  router: router,
  // 使用vuex
  store: store,
  render: h => {
    return h(App)
  }
})